package com.ccx.coachsite.api;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;

import com.ccx.coachsite.data.SystemConst;
import com.ccx.coachsite.http.EntityUtils;
import com.ccx.coachsite.model.CSException;
import com.ccx.coachsite.model.UserInfo;
import com.ccx.coachsite.model.VerifiedInfo;
import com.ccx.coachsite.ui.softmgr.SoftInfo;

/**
 * 
 *服务访问接口
 */
public class CoachSiteApiAccessor {

	public static Context appContext;
	
	public static Context getAppContext() {
		return appContext;
	}

	public static void setAppContext(Context appContext) {
		CoachSiteApiAccessor.appContext = appContext;
	}

	public static UserInfo user;
	
	private static final String TAG = "CoachSiteApiAccessor";

	/**接口API基础域名路径*/
	public static final String SERVER_URL = "http://bbx2.sj.91.com/"; //测试域名
	//public static final String BASE_URL = "http://117.27.144.30"; // "http://www.yyzl.me";
	public static final String BASE_URL = "http://42.120.53.229";  //"http://117.27.144.30";  
	public static final String APP_DOWN_URL = BASE_URL+"/down/assistant.apk";
	
	/*登陆注册模块 Begin*/
	/**用户登陆*/
	private static final String  API_LOGIN_VERIFY = BASE_URL+"/user/login.html";
	/*登陆注册模块 End*/
	

	
	/**
	 * 用户认证
	 * @return
	 * @throws Exception
	 */
	public static VerifiedInfo verify() throws Exception{
        
        String jsonString = null;
        
        try {
        	jsonString = BaseAuthenicationHttpClient.doRequest(API_LOGIN_VERIFY, user.tianyiPhone, user.sPassword);            
        } catch (CSException e) {//如果登录信息不正确的话, 会出现这样的exception:"received authentication challenge is null"
        	if(e.getMessage().startsWith("java.io.IOException: Received authentication challenge is null")){
        		jsonString = "error.auth.fail";
        	}else{
        		throw e;
        	}
        }
        /*
        VerifiedInfo ret = new VerifiedInfo();
        if (jsonString.equals("error.auth.fail")) {
            ret.verifyCode = VerifiedInfo.VERIFY_ERROR;
            ret.verifyMessage = "登录失败! 请核对用户名和密码";
        } else if (jsonString.equals("error.auth.over.limit ")) {
            ret.verifyCode = VerifiedInfo.VERIFY_ERROR;
            ret.verifyMessage = "登录次数过多, 请稍后再试!";
        } else {
            JSONObject json = new JSONObject(jsonString);
            ret.name = json.getString("name");
            //TODO 具体认证过后返回什么信息需要在补充
            ret.verifyCode = VerifiedInfo.VERIFY_SUCCESS;
        }
        */
        
        VerifiedInfo ret = new VerifiedInfo();
        JSONObject json = new JSONObject(jsonString);
        ret.nikeName = json.getString("nikeName");
        //TODO 具体认证过后返回什么信息需要在补充
        ret.verifyCode = VerifiedInfo.VERIFY_SUCCESS;
        
        return ret;
    }
	
	
	public static String getURLContent(String surl, String encode) {		
		InputStream is = null;
		try {
			URL url = new URL( surl );
			HttpURLConnection httpUrl = (HttpURLConnection) url.openConnection();
			httpUrl.setConnectTimeout(SystemConst.CONNECTION_TIMEOUT);
			is = httpUrl.getInputStream();			
			BufferedReader br = new BufferedReader(new InputStreamReader(is,encode));
			StringBuffer sb = new StringBuffer();
			String tmp = null;
			while ((tmp = br.readLine()) != null) {
				sb.append(tmp);
			}
			br.close();
			return sb.toString();
		} catch (Exception e) {
			Log.e(TAG, "getURLContent:" + surl);
			//Log.e(TAG, e.getMessage());
			e.printStackTrace();
		} finally {
			if (is != null) {
				try {
					is.close();
					is = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}	
	
	public static String getURLContentByPost(String pathUrl, String keyName, String keyWord, int pageNumber, String encode){

		/* 建立HTTP Post连线 */
		HttpPost httpRequest = new HttpPost(pathUrl);
		// Post运作传送变数必须用NameValuePair[]阵列储存
		// 传参数 服务端获取的方法为request.getParameter("name")
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(keyName, keyWord));
		params.add(new BasicNameValuePair("pageNumber", pageNumber+""));
		
		try {

			// 发出HTTP request
			httpRequest.setEntity(new UrlEncodedFormEntity(params, encode));
			// 取得HTTP response
			HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);

			// 若状态码为200 ok
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				// 取出回应字串
				String strResult = EntityUtils.toString(httpResponse.getEntity());
				return strResult;
			} else {
				System.out.println("Error Response"+ httpResponse.getStatusLine().toString());
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}
	
	public static String getURLContentByPostForWeiBo(String pathUrl, String userID,String toShareUserIds,
			String id, String userType, int shareType, String shareContent, String encode, String flag){
		
		/* 建立HTTP Post连线 */
		HttpPost httpRequest = new HttpPost(pathUrl);
		// Post运作传送变数必须用NameValuePair[]阵列储存
		// 传参数 服务端获取的方法为request.getParameter("name")
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("userId", userID));
		params.add(new BasicNameValuePair("toShareUserIds", toShareUserIds));
		params.add(new BasicNameValuePair("id", id));
		params.add(new BasicNameValuePair("userType", userType));
		params.add(new BasicNameValuePair("shareContent", shareContent));
		params.add(new BasicNameValuePair("flag", flag==null?"":flag));
		
		try {

			// 发出HTTP request
			httpRequest.setEntity(new UrlEncodedFormEntity(params, encode));
			// 取得HTTP response
			HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);

			// 若状态码为200 ok
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				// 取出回应字串
				String strResult = EntityUtils.toString(httpResponse.getEntity());
				return strResult;
			} else {
				System.out.println("Error Response"+ httpResponse.getStatusLine().toString());
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}
	
	
	public static String getFilePath(SoftInfo softInfo){
		return SystemConst.DOWNLOAD_DIR+softInfo.getPkgName()+"-"+softInfo.getAvailVersionCode()+".apk";
	}
}



